package cn.jinjimi.app.custom.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.View;

import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.QuesCode;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.event.CustomChangeEvent;
import cn.jinjimi.app.custom.event.CustomGetInfoEvent;
import cn.jinjimi.app.custom.event.CustomerListChangeEvent;
import cn.jinjimi.app.custom.event.CustomerSearchEvent;
import cn.jinjimi.app.custom.event.TransferCustomEvent;
import cn.jinjimi.app.custom.manager.CustomsManager;
import cn.jinjimi.app.custom.ui.adapter.CustomerAllAdapter;
import cn.jinjimi.app.store.entity.ClueEntity;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.SideBar;
import cn.jinjimi.app.main.widget.XListView.XListView;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择客户
 * Created by Jinsen on 2015/6/2.
 * <p/>
 * mobify 2015/11/17 客户跟进记录的选择界面,选择贺卡接受人的客户列表
 * mobify 2017/1/13  客户线索关联客户
 */
public class SelectCustomActivity extends ToolBarCommonActivity implements
        SideBar.OnTouchingLetterChangedListener, CustomerAllAdapter.onActionClickListener {

    private XListView mListView = null;
    private CustomerAllAdapter mAdapter = null;
    private SideBar mSideBar;

    private ClueEntity mClueEntity;
    private boolean haveSamePhone;

    private Custom selectedCustom;

    private static int mQuesCode;

    public static void launch(Activity startActivity, int quescode) {
        launch(startActivity, null, quescode);
    }

    public static void launch(Activity startActivity, ClueEntity clueEntity, int quesCode) {
        if (startActivity == null)
            return;
        mQuesCode = quesCode;
        Intent intent = new Intent(startActivity, SelectCustomActivity.class);

        if (clueEntity != null) {
            intent.putExtra(BundleKey.PARAM_CLUE, clueEntity);
        }
        startActivity.startActivityForResult(intent, quesCode);
    }

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_select_customlist);
        setTitle(getString(R.string.custom_select_title));
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mSideBar = (SideBar) findViewById(R.id.layout_sideBar);
        mListView = (XListView) findViewById(R.id.listview);
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(false);
        mAdapter = new CustomerAllAdapter(SelectCustomActivity.this);
        mListView.setAdapter(mAdapter);

    }

    protected void initListener() {
        mSideBar.setOnTouchingLetterChangedListener(this);
        mAdapter.setOnActionClickListener(this);
        findViewById(R.id.customer_header_search).setOnClickListener(this);
    }

    protected void initData() {
        if (getIntent().hasExtra(BundleKey.PARAM_CLUE)) {
            mClueEntity = (ClueEntity) getIntent().getSerializableExtra(BundleKey.PARAM_CLUE);
        }
        getCustomItems();
        ToastUtil.showLoading(SelectCustomActivity.this);
    }

    private void getCustomItems() {
        if (mClueEntity != null && StringUtils.isNotEmpty(mClueEntity.phone)) {
            CustomsManager.getInstance().searchCustomertWithPhone(mClueEntity.phone);
            findViewById(R.id.customer_header_search).setEnabled(false);
        } else {
            CustomsManager.getInstance().getCustoms();
            findViewById(R.id.customer_header_search).setEnabled(true);
        }
    }

    private void setAllCustoms() {
        if (mAdapter == null)
            return;
        mAdapter.setIfShowSamePhone(false);
        mAdapter.setItems(CustomsManager.getInstance().getCustomsList());
        updateIndexFlag(CustomsManager.getInstance().getCustomsList());
        updateLayout();
    }

    /**
     * 更新右侧字母索引
     *
     * @param customers
     */
    private void updateIndexFlag(List<Custom> customers) {
        List<String> indexFlag = new ArrayList<String>();
        String[] chars = new String[indexFlag.size()];
        mSideBar.setIndexChars(indexFlag.toArray(chars));
        mSideBar.setVisibility(View.VISIBLE);
    }

    public void updateLayout() {
        if (mAdapter.isEmpty()) {
            mListView.setVisibility(View.GONE);
            ToastUtils.toastMessage(this, "暂无客户，请先添加客户");
        } else {
            mListView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTouchingLetterChanged(String s) {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.customer_header_search:
                searchCustomer();
                break;
        }
    }

    /* 搜索客户 */
    private void searchCustomer() {
        if (haveSamePhone)
            CustomSearchActivity.launch(SelectCustomActivity.this, mAdapter.getItems(), mQuesCode);
        else {
            CustomSearchActivity.launch(SelectCustomActivity.this, true, mQuesCode);
        }
    }

    @Override
    public void onItemClick(Custom custom) {
        switch (mQuesCode) {
            case QuesCode.QuestSelectClientCode:
                selectCustomer(custom);
                break;
            case QuesCode.QuestSelectTranferCode:
                doTransferCutomer(custom);
                break;
        }
    }

    @Override
    public void onItemLongClick(Custom custom) {

    }

    /* 弹出显示关联提醒的dialog */
    private void doTransferCutomer(final Custom custom) {
        selectedCustom = custom;
        getAlertDialog().setTitle(String.format(getString(R.string.clue_transfer_to), custom.name))
                .setMessage(getString(R.string.clue_transfer_msg))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LoadingDialog.showForce(SelectCustomActivity.this, getString(R.string.transfer_customing));
                        CustomerController.transferCustom(mClueEntity.clueId, custom.customerId);

                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    private void selectCustomer(Custom custom) {
        showLoadingIndicator();
        CustomsManager.getInstance().getCustomInfo(custom.customerId);
    }

    /* 监听获取客户信息 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onfinal(final CustomGetInfoEvent event) {
        hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:
                if (event.data != null) {
                    Intent it = new Intent();
                    it.putExtra(BundleKey.PARAM_CUSTOM, event.data);
                    setResult(Activity.RESULT_OK, it);
                    finish();
                } else {
                    ToastUtils.toastMessage(SelectCustomActivity.this, getString(R.string.error_bad_network));
                }

                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(SelectCustomActivity.this, getString(R.string.error_bad_network));
                break;
        }
    }

    /* 列表数据有变化，更新和添加 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomChangeEvent(CustomChangeEvent event) {
        if (event.changeEvent == CustomChangeEvent.EVENT_ADD || event.changeEvent == CustomChangeEvent.EVENT_UPDATE) {
            getCustomItems();
        }
        hideLoadingIndicator();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomerListChangeEvent(CustomerListChangeEvent event) {
        TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
            @Override
            public void run() {
                hideLoadingIndicator();
            }
        });
        if (mClueEntity == null || StringUtils.isEmpty(mClueEntity.phone)) {
            setAllCustoms();
        } else {
            getCustomItems();
        }
    }

    /* 监听查询相同手机号码的问题 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomerSearchEvent(CustomerSearchEvent event) {
        TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
            @Override
            public void run() {
                hideLoadingIndicator();
                findViewById(R.id.customer_header_search).setEnabled(true);
            }
        });

        if (event.mResult == null || mClueEntity == null || !event.mResult.getPhone().equals(mClueEntity.phone))
            return;

        if (event.mResult.getList().isEmpty()) {
            setAllCustoms();
        } else {
            haveSamePhone = true;
            updateIndexFlag(event.mResult.getList());
            mAdapter.setItems(event.mResult.getList());
            mAdapter.setIfShowSamePhone(true);
            updateLayout();
        }
    }

    /* 监听关联单个用户的回调 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTransferCustomEvent(TransferCustomEvent event) {

    }

    /* 客户被删或为空的处理 */
    public void customNull() {
        getAlertDialog().setTitle(getString(R.string.custom_null))
                .setMessage("")
                .setRightBtn(getString(R.string.custom_i_know), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        CustomsManager.getInstance().deleteCustom(selectedCustom, true);
                        EventBus.getDefault().post(new CustomChangeEvent(selectedCustom, CustomChangeEvent.EVENT_DELETE));
                    }
                });
        getAlertDialog().setCancelable(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.ONE_BUTTON);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        Custom custom = null;
        if (data.hasExtra(BundleKey.PARAM_CUSTOM))
            custom = (Custom) data.getSerializableExtra(BundleKey.PARAM_CUSTOM);

        switch (requestCode) {
            case QuesCode.QuestSelectTranferCode:
                if (custom != null)
                    doTransferCutomer(custom);
                break;
            case QuesCode.QuestSelectClientCode:
                if (custom != null)
                    CustomsManager.getInstance().getCustomInfo(custom.customerId);
                break;
        }

    }
}
